<?php

namespace Admin\Controller; //当前命名空间跟文件目录一样
use Common\Common\CommonController;  //继承公共控制器类，时刻检测管理员身份
class CategoryController extends CommonController
{
	//显示所有分类
	public function showList()
	{
		//检查管理员登录信息
		$this->checkAdmin();
		$model = M('Category');
		$categoryInfo = $model->select();
		$this->assign('categoryInfo', $categoryInfo);
		$this->display();
	}

	//添加分类
	public function add()
	{
		//检查管理员登录信息
		$this->checkAdmin();
		if (IS_POST) {
			$category_name = I('post.cn');
			$model = M('Category');
			if ($model->where(array('category_name' => $category_name))->find()) {
				$this->error("该分类已存在！无法添加", U('?m=admin&c=category&a=showList'));
				die;
			}
			if ($model->add(array("category_name" => $category_name))) {
				$this->success("分类创建成功", U('?m=admin&c=category&a=showList'));
				die;
			}
			$this->error("分类创建失败", U('?m=admin&c=category&a=showList'));
			die;
		}
		$this->display();
	}

	//删除分类
	public function Cdelete()
	{
		//检查管理员登录信息
		$this->checkAdmin();
		$category_id = I('ci');
		$model = M('category');
		if ($info = $model->where(array('category_id' => $category_id))->find()) {
			if ($model->where(array('category_id' => $category_id))->delete() !== false) {
				//将所有该分类的商品变为无分类的编号1
				$modelGoods = M('Goods');
				$modelGoods->where(array('category_id' => $category_id))->save(array('category_id' => 1));
				$this->success("删除分类成功,该分类下的商品已还原", U('?m=admin&c=category&a=showList'));
				die;
			}
			$this->error("删除失败，未知错误！", U('?m=admin&c=category&a=showList'));
			die;
		}
		die;
		$this->error("该分类不存在！无法删除", U('?m=admin&c=category&a=showList'));
	}
}
